import { useMemo } from 'react';
import { useTerminalStore } from '../stores';
import { iconMapping } from '../utils';

/**
 * 处理python-player输出的hook
 */
export const useOutputHandler = () => {
  const terminalStore = useTerminalStore();

  const outputListener = useMemo(() => (text) => {
    // 处理空字符串 - 清空输出
    if (text === '') {
      terminalStore.clearOutput();
      return;
    }
    
    // 处理特殊格式的输出
    if (text.includes('##ERROR_START##')) {
      // 错误输出
      const errorMatch = text.match(/##ERROR_START##(.*?)##ERROR_END##/s);
      if (errorMatch) {
        const errorContent = errorMatch[1];
        const lines = errorContent.split('\n').filter(line => line.trim());
        
        lines.forEach(line => {
          if (line.includes('行 ')) {
            // 解析错误信息
            const lineMatch = line.match(/行 ##LINE##(\d+)##LINE##/);
            const colMatch = line.match(/列 ##COLUMN##(\d+)##COLUMN##/);
            const messageMatch = line.match(/##MESSAGE##(.*)##MESSAGE##/);
            
            const errorInfo = {};
            if (lineMatch) errorInfo.line = parseInt(lineMatch[1]);
            if (colMatch) errorInfo.column = parseInt(colMatch[1]);
            if (messageMatch) errorInfo.message = messageMatch[1].trim();
            
            terminalStore.addErrorLine(line, errorInfo);
          } else {
            terminalStore.addErrorLine(line);
          }
        });
      }
    } else if (text.includes('##WARNING_START##')) {
      // 警告输出
      const warningMatch = text.match(/##WARNING_START##(.*?)##WARNING_END##/s);
      if (warningMatch) {
        const warningContent = warningMatch[1];
        const lines = warningContent.split('\n').filter(line => line.trim());
        
        lines.forEach(line => {
          terminalStore.addWarningLine(line);
        });
      }
    } else if (text.includes('##SYSTEM_START##')) {
      // 系统消息输出
      const systemMatch = text.match(/##SYSTEM_START##(.*?)##SYSTEM_END##/s);
      if (systemMatch) {
        const systemContent = systemMatch[1].trim();
        
        // 解析系统消息格式: title │ duration │ timestamp
        const parts = systemContent.split('│').map(p => p.trim());
        const title = parts[0] || '系统消息';
        
        // 根据标题内容推断图标类型
        const iconType = iconMapping.getIconTypeFromMessage(title);
        
        // 解析时间信息
        let timestamp = '', duration = '';
        
        for (let i = 1; i < parts.length; i++) {
          const part = parts[i];
          if (part.includes('⏱️') || part.includes('耗时') || part.includes('duration')) {
            duration = part.replace(/⏱️|耗时|duration/gi, '').trim();
          } else if (part.includes('🕐') || part.includes('时间') || part.includes('time')) {
            timestamp = part.replace(/🕐|时间|time/gi, '').trim();
          }
        }
        
        terminalStore.addSystemLine(systemContent, iconType, title, duration, timestamp);
      }
    } else {
      // 普通输出 - 按行处理
      const lines = text.split('\n');
      lines.forEach((line, index) => {
        // 处理所有行，包括空行，以保持换行符
        if (index === lines.length - 1 && line === '') {
          // 最后一行是空行，不添加（避免末尾多余的换行）
          return;
        }
        terminalStore.addOutputLine(line);
      });
    }
  }, [terminalStore]);

  return { outputListener };
};
